﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using SmartMotion.Core.Mgrs;

namespace SmartMotion.Core
{
    public class PointsMgr
    {
        #region 单例

        private static readonly Lazy<PointsMgr> Instance = new Lazy<PointsMgr>(() => new PointsMgr());
        private string _filePath = string.Empty;

        private PointsMgr()
        {
            Open();
        }

        public static PointsMgr Ins { get; } = Instance.Value;

        #endregion 单例

        #region 属性
        
        public string FilePath
        {
            get
            {
                try
                {
                    _filePath = Path.GetFullPath(ProductMgr.Ins.FilePath).Replace(".xml", "\\");
                    _filePath += Path.GetFileNameWithoutExtension(ProductMgr.Ins.FilePath);
                    _filePath += ".points";
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
               
                return _filePath;
            }
        }

        public string ProductName { get; set; }

        //点位

        private ConcurrentDictionary<string, VarInfo> _points;

        public ConcurrentDictionary<string, VarInfo> Points
        {
            get
            {
                _points = VarMgr.Ins.Vars[VarMgr.Points];
                return _points;
            }
        }

        #endregion 属性

        public void Open()
        {
            VarMgr.Ins.LoadDic(VarMgr.Points, FilePath, false);
        }

        public void Save()
        {

            VarMgr.Ins.SaveDic(VarMgr.Points, FilePath);
        }

        public bool AddPoints(string name, string station, double[] position)
        {
            return Points.TryAdd($"{station}_{name}", new VarInfo()
            { Name = name, Type = typeof(double[]).FullName, Group = station, Value = position });
        }

        public List<VarInfo> GetPoints(string station)
        {
            return (from varInfo in Points where varInfo.Value.Group == station select varInfo.Value).ToList();
        }
    }
}
